package com.lx;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor implements Runnable{

	private InputStream in;
	private PrintStream out;
	private static final String rootPath = "D:\\JAVA_HOME\\WorkSpacesJunoSR2_64\\WebServer\\Files\\";
	
	public Processor(Socket socket){
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void run() {
		String fileName = parse(in);
		sendFile(fileName);
	}
	
	private void sendFile(String fileName) {
		File file = new File(rootPath + fileName);
		if(!file.exists()){
			sendErrorMessage(404, "File Not Found");
			return;
		}
		
		try {
			InputStream in = new FileInputStream(file);
			byte[] content = new byte[(int)file.length()];
			in.read(content);
			out.println("HTTP/1.0 200 ok");
			out.println("content-length:" + content.length);
			out.println();
			out.write(content);
			out.flush();
			out.close();
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	private String parse(InputStream in) {
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String filename = null;
		try {
			String httpMessage = br.readLine();
			String[] content = httpMessage.split(" ");
			if(content.length != 3){
				sendErrorMessage(400, "Client Query Error!");
				return null;
			}
			
			System.out.println("code:" + content[0] + ", fileName:"
					+ content[1] + ", http version:" + content[2]);
			
			filename = content[1];
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return filename;
	}
	
	
	private void sendErrorMessage(int errorCode, String errorMessage) {
		out.print("HTTP/1.0 " + errorCode + " " + errorMessage);
		out.print("content-type: text/html");
		out.println();
		out.println("<html>");
		out.println("<title>Error Message</title>");
		out.println("<body>");
		out.println("<h1>ErrorCode"+ errorCode +", Message:"+ 
						errorMessage+"</h1>");
		out.println("</body>");
		out.println("</html>");
		out.flush();
		out.close();
		try {
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
